package com.chenglai.goods.service;

import com.chenglai.commonutils.common.DateFormatHelper;
import com.chenglai.goods.dao.GoodsCartMapper;
import com.chenglai.goods.pojo.GoodsCart;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 类描述：
 *
 * @Author rxh
 * @Date 2023/11/17 14:24
 */
@Service
public class GoodsCartServiceImpl implements GoodsCartService {

    @Resource
    private GoodsCartMapper goodsCartMapper;

    @Override
    public List<GoodsCart> getGoodsCartList(Integer userId) {
        Example example = new Example(GoodsCart.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        example.orderBy("createTime").asc();
        return goodsCartMapper.selectByExample(example);
    }

    @Override
    public Map<String, Object> addGoodsToGoodsCart(GoodsCart goodsCart) {
        Map<String, Object> data = new HashedMap<>();
        //判断库存是否够
        Integer count = goodsCartMapper.getInventoryCount(goodsCart.getInventoryId());
        if (count < goodsCart.getGoodsAmount()) {
            data.put("msg", "库存不足");
            data.put("flag", "error");
            return data;
        } else {
            goodsCart.setCreateTime(DateFormatHelper.currentTimes());
            goodsCartMapper.insertSelective(goodsCart);
            data.put("flag", "success");
            data.put("msg", "添加成功");
            return data;
        }


    }

    @Override
    public void delGoodsCart(String ids) {
        Example example = new Example(GoodsCart.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("cartId", Arrays.asList(ids));
        goodsCartMapper.deleteByExample(example);
    }

    @Override
    public GoodsCart detail(Integer cartId) {
        return goodsCartMapper.selectByPrimaryKey(cartId);
    }
}
